package DataStructures.Stack;

/**
 * @author ：ALi
 * @date ：Created in 2021/11/2 15:24
 * @description：入栈+出栈
 * @modified By：
 * @version: $
 */
public class stack {

    public static void main(String[] str){
        //测试栈的功能
        ArrayStack stack = new ArrayStack(5);
        //给栈赋值
        for (int i = 0;i<5;i++){
            stack.push(i);
        }
        //测试出栈与入栈
        stack.push(5);
        stack.list();
        System.out.println("---------------");
        int res1 = stack.pop();
        System.out.println(res1);
        stack.list();
        System.out.println("---------------");
        int res2 = stack.pop();
        System.out.println(res2);
        stack.list();

    }

}
/**
 * create by: ALi
 * description: 栈的类
 * create time: 2021/11/2 15:47
 *
  * @Param: null
 * @return
 */
class ArrayStack{
    private int maxSize;
    private int[] stack;
    private int top = -1;

    public ArrayStack(int maxSize){
        this.maxSize = maxSize;
        this.stack = new int[this.maxSize];
    }
    /**
     * create by: ALi
     * description: 判断栈满
     * create time: 2021/11/2 15:29
     *
      * @Param:
     * @return  true:满
     */
    public boolean isFull(){
        if(top == maxSize -1 ){
            return true;
        }else {
            return false;
        }
    }

    /**
     * create by: ALi
     * description: 判断栈是否为空
     * create time: 2021/11/2 15:29
     *
      * @Param:
     * @return true:空
     */
    public boolean isEmpty(){
        if(top == -1){
            return true;
        }else {
            return false;
        }
    }

    /**
     * create by: ALi
     * description: 出栈
     * create time: 2021/11/2 15:32
     *
      * @Param: null
     * @return 出栈的数据
     */
    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("栈为空！");
        }
        int res = stack[top];
        top--;
        return res;

    }
    /**
     * create by: ALi
     * description: 入栈
     * create time: 2021/11/2 15:33
     *
      * @Param: num:入栈的数据
     * @return
     */
    public void push(int num){
        if(isFull()){
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top] = num;
    }

    /**
     * create by: ALi
     * description: 遍历栈
     * create time: 2021/11/2 15:33
     *
      * @Param: null
     * @return
     */
    public void list(){
        if (isEmpty()){
            System.out.println("栈空");
            return;
        }
        for (int i = top;i>= 0;i--){
            System.out.printf("stact[%d]=%d\n",i,stack[i]);
        }
    }

    //取栈顶的元素，但是不弹出栈
    public int peek(){
        return stack[top];
    }

}